package person.twj.orderservice;

import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.spring.annotation.GlobalTransactional;
import io.seata.tm.api.GlobalTransactionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import person.twj.common.feign.OrderFeignService;
import person.twj.common.feign.StorageFeignService;

@RestController
public class BusinessController {
    @Autowired
    private StorageFeignService storageService;
    @Autowired
    private OrderFeignService orderService;

    private final String COMMODITY_CODE = "123456";
    private final int ORDER_COUNT = 100;
    private final String USER_ID = "128";


    // 用户购买商品 port:8082
    // 商品库存-1
    // 订单新增
//    @GlobalTransactional(timeoutMills = 300000, name = "service-web-tx")
//    @GlobalTransactional(rollbackFor = Exception.class,timeoutMills = 30000,lockRetryInternal=3000,lockRetryTimes=10)
    @GlobalTransactional
    @GetMapping(value = "/seata/feign")
    public String feign(@RequestParam("type") int type) {



        try {
            String result = storageService.storage(COMMODITY_CODE, ORDER_COUNT, type);

            if (!"SUCCESS".equals(result)) {
                throw new RuntimeException();
            }

            result = orderService.order(USER_ID, COMMODITY_CODE, ORDER_COUNT, type);

            if (!"SUCCESS".equals(result)) {
                throw new RuntimeException();
            }

            if (type == 4) {
//                Thread.sleep(30*1000);// 30秒
                throw new RuntimeException("type=4");
            }

            return "SUCCESS";
        }catch (Exception e){
            e.printStackTrace();
            try {
                GlobalTransactionContext.reload(RootContext.getXID()).rollback();
            } catch (TransactionException ex) {
                throw new RuntimeException(ex);
            }
        }
        return "FAILED";

    }
}
